<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
<!--      <el-form-item label="拖轮ClientId" prop="deviceClientId">-->
<!--        <el-input-->
<!--            v-model="queryParams.deviceClientId"-->
<!--            placeholder="请输入拖轮ClientId"-->
<!--            clearable-->
<!--            @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="拖轮名称" prop="deviceName">
        <el-select v-model="queryParams.deviceName" placeholder="请选择拖轮名称" @change="handleQuery" clearable filterable>
          <el-option
              v-for="item in deviceOption"
              :key="item.value"
              :label="item.label"
              :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="拖轮代码" prop="deviceClientId">
        <el-select v-model="queryParams.deviceClientId" placeholder="请选择拖轮代码" @change="handleQuery" clearable filterable>
          <el-option
              v-for="item in deviceOption"
              :key="item.value"
              :label="item.value"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="连接状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择连接状态" @change="handleQuery" clearable>
          <el-option
              v-for="item in dict.type.remote_computer_status"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" 
              :data="remoteList"
              max-height="650px"
              :row-class-name="rowClassNameByStatus"
              border>
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="拖轮名称" align="center" prop="deviceName" width="200"/>
      <el-table-column label="拖轮代码" align="center" prop="deviceClientId" width="200"/>
      <el-table-column label="连接状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.status == '0'">离线</span>
          <span v-if="scope.row.status == '1'" style="color: blue">空闲</span>
          <span v-if="scope.row.status == '2'" style="color: red;font-weight: bold">正在远控</span>
        </template>
      </el-table-column>
      <el-table-column label="最后响应时间" align="center" prop="receiveTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiveTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="硬盘信息" align="center" prop="hardDiskInfo" width="500">
        <template slot-scope="scope">
          <span :style="compareUsageRate(scope.row)">{{scope.row.hardDiskInfo}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-s-platform"
              :disabled="scope.row.status==='0' || isConnecting(scope.row)"
              @click="handleInstall(scope.row)"
              v-hasPermi="['remoteControl:remote:install']"
          >发起连接</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              :disabled="isConnecting(scope.row)===false"
              @click="handleUninstall(scope.row)"
              v-hasPermi="['remoteControl:remote:uninstall']"
          >解除连接</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-document-copy"
              :disabled="isConnecting(scope.row)===false"
              @click="copyUrl(scope.row)"
              v-hasPermi="['remoteControl:remote:copyUrl']"
          >复制远控url</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-document-copy"
              :disabled="isConnecting(scope.row)===false"
              @click="openWebPage(scope.row)"
              v-hasPermi="['remoteControl:remote:openWebPage']"
          >打开远控界面</el-button>
<!--          <el-button-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              icon="el-icon-s-marketing"-->
<!--              @click=""-->
<!--              v-hasPermi="['remoteControl:remote:largeScreen']"-->
<!--          >监控大屏</el-button>-->
          <el-button
              size="mini"
              type="text"
              icon="el-icon-s-marketing"
              @click="deleteDevice(scope.row)"
              :disabled="scope.row.status !== '0'"
              v-hasPermi="['remoteControl:remote:delete']"
          >删除对象</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {listRemote, install, uninstall, openWeb, deleteDevice} from "@/api/remoteControl/remote";
import deviceOptionMixin from "@/mixin/deviceOptionMixin";

export default {
  name: "Remote",
  dicts: ['remote_computer_status'],
  mixins:[deviceOptionMixin],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 拖轮电脑远程操控表格数据
      remoteList: [],
      // 远控会话信息列表
      sessionInfoList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        receiveTime: null,
        status: null,
        hardDiskInfo: null,
        deviceClientId: null,
        deviceName: null
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询拖轮电脑远程操控列表 */
    getList() {
      this.loading = true;
      listRemote(this.queryParams).then(response => {
        this.remoteList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 发起远控*/
    async handleInstall(row) {
      this.loading = true
      console.log(row.deviceClientId)
      try {
        const response = await install(row.deviceClientId)
        let exist = false
        // 判断sessionInfoList中是否已存在，存在则更新，不存在则插入
        for (let i = 0; i < this.sessionInfoList.length; i++) {
          if (this.sessionInfoList[i].deviceClientId===response.data.deviceClientId){
            exist = true
            // 删除原来的
            this.sessionInfoList.splice(i,1)
            // 重新插入新的
            this.sessionInfoList.push({deviceClientId:response.data.deviceClientId,url:response.data.url})
            break
          }
        }
        if (exist===false){
          this.sessionInfoList.push({deviceClientId:response.data.deviceClientId,url:response.data.url})
        }
        // 刷新列表
        this.getList()
        this.$message.success(response.data.msg)
        console.log(this.sessionInfoList)
      }catch (e){
        this.loading = false
      }finally {
        this.loading = false
      }
    },
    /** 结束远控*/
    async handleUninstall(row) {
      this.loading = true
      try {
        const response = await uninstall(row.deviceClientId)
        // 从sessionInfoList中删除会话信息
        for (let i = 0; i < this.sessionInfoList.length; i++) {
          if (this.sessionInfoList[i].deviceClientId===row.deviceClientId){
            this.sessionInfoList.splice(i,1)
          }
        }
        // 刷新列表
        this.getList()
        this.$message.success(response.msg)
        console.log(this.sessionInfoList)
      }catch (e){
        this.loading = false
      }finally {
        this.loading = false
      }
    },
    /** 读取会话信息*/
    getSessionInfo(deviceClientId){
      for (let i = 0; i < this.sessionInfoList.length; i++) {
        if (this.sessionInfoList[i].deviceClientId===deviceClientId){
          return this.sessionInfoList[i]
        }
      }
      return null
    },
    /** 实现复制远控url*/
    copyUrl(row) {
      let input = document.createElement('input')
      const sessionInfo = this.getSessionInfo(row.deviceClientId)
      if (sessionInfo!==null){
        // 拼接deviceName
        var url = sessionInfo.url + "&deviceName=" + row.deviceName
        input.value = url
      }
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      this.$message.success('复制成功!')
      document.body.removeChild(input)
    },
    /** 前端直接打开远控url*/
    openWebPage(row){
      const sessionInfo = this.getSessionInfo(row.deviceClientId)
      if (sessionInfo!==null){
        // 拼接deviceName
        var url = sessionInfo.url + "&deviceName=" + row.deviceName
        window.open(url)
      }
    },
    deleteDevice(row){
      this.$confirm('确认删除该远程设备吗？')
          .then(() => {
            deleteDevice({deviceClientId:row.deviceClientId}).then(()=>{
              this.$message.success('对象删除成功！')
              // 刷新列表
              this.getList()
            }).catch(()=>{
              this.$message.error('对象删除失败！')
            })
          }).catch(() => {});
    },
    /** 判断对象当前是否已发起远控*/
    isConnecting(row){
      const sessionInfo = this.getSessionInfo(row.deviceClientId)
      return sessionInfo !== null
    },
    /** 比较硬盘使用率并根据使用率返回样式*/
    compareUsageRate(row){
      var usageRate = row.hardDiskInfo.split("已使用")[1].split("%")[0]
      usageRate = parseFloat(usageRate)
      if (usageRate >= 90.00){
        return 'color: darksalmon;font-weight: bold'
      }else{
        return ''
      }
    },
    /** 根据status返回行背景色样式*/
    rowClassNameByStatus({row}){
      if (row.status==='0'){
        return 'row-offline'
      }
      if (row.status==='1'){
        return 'row-waiting'
      }
      if (row.status==='2'){
        return 'row-connecting'
      }
    }
  }
};
</script>

<style>
.row-offline {
  background-color: rgb(245, 245, 245) !important;
}
.row-waiting {
  background-color: rgb(240, 249, 235) !important;
}
.row-connecting {
  background-color: rgb(240, 254, 254) !important;
}
</style>
